﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using MMessaging.MessagingEx.Common;
using MMessaging.MessagingEx.Services;
using System.Threading;

namespace MMessaging.Test
{
	public class UnitTest1
	{
		public static void TestMethod1()
		{
			var dispatcher1 = new MServiceDispatcher(
				serviceName: "dispatcher 1",
				logXImplementor: null,
				intervallTimeoutCheckCancel: 100);
			var dispatcher2 = new MServiceDispatcher(
				serviceName: "dispatcher 2",
				logXImplementor: null,
				intervallTimeoutCheckCancel: 100);
			dispatcher1.StartAsync();
			dispatcher2.StartAsync();

			var waitHandle = new ManualResetEvent(false);

			dispatcher1.BeginInvoke(
				"task 1",
				Task1,
				dispatcher2,
				waitHandle);

			waitHandle.WaitOne();
		}

		private static IEnumerable<MMessageTask<object>> Task1(
			MMessagingHandlerContext<object> context,
			MServiceDispatcher dispatcher2,
			ManualResetEvent waitHandle)
		{
			var threadName = Thread.CurrentThread.Name;
			context.Sleep("sleep on dispatcher 1", 2000);
			dispatcher2.BeginInvoke(
				"task 2",
				Task2,
				1000);
			int s = 12;
			yield return context.CallOnDispatcher(
				"task 2 synchron",
				100000,
				dispatcher2,
				Task2,
				5000);
			waitHandle.Set();
		}

		private static IEnumerable<MMessageTask<object>> Task2(
			MMessagingHandlerContext<object> context,
			int a)
		{
			var threadName = Thread.CurrentThread.Name;
			yield return context.Sleep("sleep on dispatcher 2", a);
			yield break;
		}
	}
}
